import React from 'react';
import { Button, Form, Input, message, Modal, Select, Tag } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';

class SynonymModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      synonymList: [],
      corewordList: []
    }
  }
  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  getSynonymList = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'answerRecords/getSynonym',
      payload: { query: '', page: 1, limit: 9999999 },
      callback: res => {
        // console.log(res);
        this.setState({ corewordList: res.list })
      },
    });
  }

  changeCoreword = value => {
    const { corewordList } = this.state;
    let synonymList = [];
    corewordList.map(item => {
      if (item.id === value) {
        synonymList = item.aligns
      }
    });
    this.setState({ synonymList });
    // console.log(corewordList, synonymList);
  }

  onSubmit = () => {
    const { dispatch, form, currentUser } = this.props;
    const { corewordList, synonymList } = this.state;
    let coreword = "";
    form.validateFields((errors, values) => {
      if (!errors) {
        if (values.synonym.replace(/[\ |\s*(.*?)\s+$|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\，|\。|\“|\”|\‘|\’|\¥|\？|\（|\）|\；|\：|\、|\！|\<|\.|\>|\/|\?]/g, "").length > 20) {
          return message.error('同义词不可超过20个汉字或字母');
        };
        corewordList.map(item => {
          if (item.id === values.coreword) {
            coreword = item.word;
          }
        });

        let arr = [];
        arr.push(values.synonym);
        let saveSynonymList = arr.concat(synonymList);

        dispatch({
          type: 'answerRecords/doSubmit',
          payload: { aligns: saveSynonymList, oldWord: coreword, word: coreword, },
          callback: res => {
            // console.log(res);
            message.info(res.msg);
            this.props.onClose();
          },
        });
      }
    })
  }

  toAdd = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/knowledgeDesign/thesaurusManage', }));
  }

  render() {
    const { visible, copyText, onClose } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { synonymList, corewordList } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    return (
      <Modal title={'编辑同义词'} visible={visible} onCancel={onClose} onOk={this.onSubmit} cancelText={'取消'} okText={'确定'}>
        <Form {...formItemLayout}>
          <Form.Item label={'同义词'}>
            {getFieldDecorator('synonym', { initialValue: copyText })(<Input placeholder={'请输入同义词'} />)}
          </Form.Item>
          <Form.Item label={'核心词'}>
            {getFieldDecorator('coreword', {
              rules: [{ required: true, message: '核心词必填' }]
            })(
              <Select style={{ width: '75%' }} onChange={this.changeCoreword}>
                {corewordList.map(item => {
                  return <Select.Option value={item.id} key={item.id}>{item.word}</Select.Option>
                })}
              </Select>
            )}
            <Button type="primary" style={{ marginLeft: 10 }} onClick={this.toAdd}>新增</Button>
          </Form.Item>
          <Form.Item label={'当前同义词'}>
            {synonymList.map((item, index) => {
              let color = index % 2 == 1 ? '#87d3ac' : '#5092e1';
              return <Tag key={index} color={color}>{item}</Tag>
            })}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(SynonymModal));
